/**
 *
 * @param tree  树数据
 * @param selectedKeys  选中的所有key
 * @return  返回所有选中的节点key
 */

interface TsTree {
	id: string;
	children: TsTree[];
}
export const findSelectedNodes = (tree: TsTree[], selectedKeys: string[]): string[] => {
	// 如果当前节点为根节点，并且所有子节点都被选中，则只返回根节点key
	if (selectedKeys.includes('0')) {
		return ['0'];
	}
	const selectedNodes = [];
	for (const node of tree) {
		const nodeKey = node.id;
		const children = node.children || [];

		// 判断当前节点是否被选中
		if (selectedKeys.includes(nodeKey)) {
			let allChildrenSelected = true;

			for (const child of children) {
				const childKey = child.id;
				if (!selectedKeys.includes(childKey)) {
					allChildrenSelected = false;
					break;
				}
			}
			// 如果所有子节点都被选中，则只返回父节点key
			if (allChildrenSelected) {
				selectedNodes.push(nodeKey);
			} else {
				// 否则将已选中的子节点key加入结果数组
				for (const child of children) {
					const childKey = child.id;
					if (selectedKeys.includes(childKey)) {
						selectedNodes.push(childKey);
					}
				}
			}
		} else {
			// 如果当前节点未选中，则继续递归查找其子节点
			const childNodes = findSelectedNodes(children, selectedKeys);
			if (childNodes.length) {
				selectedNodes.push(...childNodes);
			}
		}
	}

	return selectedNodes;
};

/**
 * 从treeData的扁平数据中获取数据, 并对应 playIds 中 所在的index位置
 * @param flatObj treeData的扁平化结构
 * @param playIds 要遍历的id集合
 * @returns 返回一个新的对象数组， 数组中的每一项按照 id 在 playIds中的指定index位置存放
 */
export const findNodeByIndex = (flatObj: Record<string, any>, playIds: any[]): any[] => {
	const newList: any[] = [];
	playIds.forEach((id: string, inx: number) => {
		if (flatObj[id]) {
			newList.push(flatObj[id]);
		}
	});
	return newList;
};
/**
 * 历史调用时间间隔
 */
export const historyCallInterval = (): any => {
	let oldTime: number = Date.now();
	return () => {
		const nowTime = Date.now();
		const interval = nowTime - oldTime;
		oldTime = nowTime;
		return interval || -1;
	};
};
